# deploy.ps1
param(
    [string]$ServerIP = "81.68.152.107",
    [string]$Username = "ubuntu",
    [string]$Password = "Hakurei11",
    [string]$RemotePath = "/home/ubuntu/xibie/xibie-web/dist",
    [string]$SourcePath = "./dist",
    [string]$SshPort = "22"
)

# Set error handling
$ErrorActionPreference = "Stop"

try {
    Write-Host "Starting frontend deployment..." -ForegroundColor Green

    # Step 1: Check Node.js and npm
    Write-Host "Checking Node.js environment..." -ForegroundColor Yellow
    $nodeVersion = node --version
    $npmVersion = npm --version
    Write-Host "Node.js version: $nodeVersion" -ForegroundColor Cyan
    Write-Host "npm version: $npmVersion" -ForegroundColor Cyan

    # Step 2: Run npm build
    Write-Host "Building project..." -ForegroundColor Yellow
    npm run build

    if ($LASTEXITCODE -ne 0) {
        throw "Build failed, please check project configuration"
    }

    Write-Host "Project built successfully!" -ForegroundColor Green

    # Step 3: Check if PSCP is available
    Write-Host "Checking PSCP tool..." -ForegroundColor Yellow
    $pscpPath = Get-Command "pscp" -ErrorAction SilentlyContinue
    if (-not $pscpPath) {
        # If PSCP not in PATH, try common installation paths
        $puttyPaths = @(
            "$env:ProgramFiles\PuTTY\pscp.exe",
            "${env:ProgramFiles(x86)}\PuTTY\pscp.exe",
            "$env:USERPROFILE\Downloads\pscp.exe"
        )

        foreach ($path in $puttyPaths) {
            if (Test-Path $path) {
                $pscpPath = $path
                break
            }
        }

        if (-not $pscpPath) {
            Write-Host "PSCP not found, please install PuTTY or download pscp.exe" -ForegroundColor Red
            Write-Host "Download: https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html" -ForegroundColor Yellow
            throw "PSCP tool not found"
        }
    } else {
        $pscpPath = $pscpPath.Source
    }

    Write-Host "Using PSCP path: $pscpPath" -ForegroundColor Cyan

    # Step 4: Upload dist folder to server
    Write-Host "Uploading files to server..." -ForegroundColor Yellow

    # Create temporary zip file (optional, for better upload efficiency)
    $tempZip = "dist-$(Get-Date -Format 'yyyyMMdd-HHmmss').zip"
    Write-Host "Creating zip file: $tempZip" -ForegroundColor Cyan
    Compress-Archive -Path "$SourcePath\*" -DestinationPath $tempZip -Force

    # Upload using PSCP
    $remoteTarget = "$Username@$ServerIP`:$RemotePath"

    Write-Host "Uploading to server: $remoteTarget" -ForegroundColor Cyan

    # Upload with PSCP
    & $pscpPath -P $SshPort -pw $Password $tempZip $remoteTarget

    if ($LASTEXITCODE -ne 0) {
        throw "File upload failed"
    }

    Write-Host "Files uploaded successfully!" -ForegroundColor Green

    # Step 5: Extract files on server (optional)
    Write-Host "Processing files on server..." -ForegroundColor Yellow

    # Use Plink for remote commands
    $plinkPath = $pscpPath -replace "pscp.exe", "plink.exe"

    if (Test-Path $plinkPath) {
        $remoteCommands = @"
cd $RemotePath
unzip -o $tempZip -d .
rm $tempZip
echo "Deployment completed!"
"@

        # Execute remote commands
        & $plinkPath -P $SshPort -pw $Password $Username@$ServerIP $remoteCommands

        if ($LASTEXITCODE -ne 0) {
            Write-Host "Remote command execution may have issues, please check manually" -ForegroundColor Yellow
        }
    } else {
        Write-Host "plink.exe not found, please extract files manually on server" -ForegroundColor Yellow
    }

    # Clean up temporary file
    Remove-Item $tempZip -Force

    Write-Host "Deployment completed!" -ForegroundColor Green

} catch {
    Write-Host "Error: $_" -ForegroundColor Red
    Write-Host "Deployment failed!" -ForegroundColor Red
    exit 1
}